package cloud.tianai.captcha.demo;

import cloud.tianai.captcha.common.constant.CaptchaTypeConstant;
import cloud.tianai.captcha.generator.common.constant.SliderCaptchaConstant;
import cloud.tianai.captcha.resource.ImageCaptchaResourceManager;
import cloud.tianai.captcha.resource.ResourceStore;
import cloud.tianai.captcha.resource.common.model.dto.Resource;
import cloud.tianai.captcha.resource.common.model.dto.ResourceMap;
import cloud.tianai.captcha.resource.impl.provider.ClassPathResourceProvider;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.stereotype.Component;

import java.util.Arrays;

import static cloud.tianai.captcha.generator.impl.StandardSliderImageCaptchaGenerator.DEFAULT_SLIDER_IMAGE_TEMPLATE_PATH;

/**
 * 功能说明：负责模板和背景图存储的地方
 *
 * @author liuyang44728
 * @date 2024年04月07日 14:18
 */
@Component
public class CaptchaInitConfig implements InitializingBean {

    private static final String SLIDER_IMG_PATH = "static/images/captcha/slider";

    @Autowired
    private ResourceStore resourceStore;

    @Autowired
    private ImageCaptchaResourceManager imageCaptchaResourceManager;

    @Override
    public void afterPropertiesSet() throws Exception {
        // 滑块验证码 模板 (系统内置)
        ResourceMap template1 = new ResourceMap("default", 4);
        template1.put(SliderCaptchaConstant.TEMPLATE_ACTIVE_IMAGE_NAME, new Resource(ClassPathResourceProvider.NAME, DEFAULT_SLIDER_IMAGE_TEMPLATE_PATH.concat("/1/active.png")));
        template1.put(SliderCaptchaConstant.TEMPLATE_FIXED_IMAGE_NAME, new Resource(ClassPathResourceProvider.NAME, DEFAULT_SLIDER_IMAGE_TEMPLATE_PATH.concat("/1/fixed.png")));
        ResourceMap template2 = new ResourceMap("default", 4);
        template2.put(SliderCaptchaConstant.TEMPLATE_ACTIVE_IMAGE_NAME, new Resource(ClassPathResourceProvider.NAME, DEFAULT_SLIDER_IMAGE_TEMPLATE_PATH.concat("/2/active.png")));
        template2.put(SliderCaptchaConstant.TEMPLATE_FIXED_IMAGE_NAME, new Resource(ClassPathResourceProvider.NAME, DEFAULT_SLIDER_IMAGE_TEMPLATE_PATH.concat("/2/fixed.png")));

        // 1. 添加模板
        resourceStore.addTemplate(CaptchaTypeConstant.SLIDER, template1);
        resourceStore.addTemplate(CaptchaTypeConstant.SLIDER, template2);
        // 2. 添加自定义背景图片
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Arrays.stream(resolver.getResources("classpath:" + SLIDER_IMG_PATH + "/*")).forEach(resource -> {
            resourceStore.addResource(CaptchaTypeConstant.SLIDER, new Resource("classpath", SLIDER_IMG_PATH + "/" + resource.getFilename(), "default"));
        });
    }
}
